﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microhard.WeixinMP.Models;
using Microhard.Core;
using Microhard.WeixinMP.Interfaces;
using Microhard.WeixinMP.Impls;
using System.Threading;
using FluentValidation;
using Microhard.WeixinMP.Validators;

namespace Microhard.WeixinMP.Filter
{
    public class RecordMsgInDB : ActionFilterAttribute
    {
        public string WXMPUserName { set; get; }
        private Thread sending = null;
        private IWeixinMP wmp = IoC.Resolve<IWeixinMP>();

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IWXMPAccount wmap = IoC.Resolve<IWXMPAccount>();
            filterContext.HttpContext.Items["MPAccountUser"] = wmap.GetModelByModel(new WXMPAccountModel
            {
                UserName = this.WXMPUserName
            });
        }

        void CheckMsg(object objMsg)
        {
            //记录到数据库 
            RequestServiceModel msg = objMsg as RequestServiceModel;
            if (msg == null)
                return;
            if (!wmp.RecordMessage(msg, WXMPUserName))
            {
                Log.Error("RecordMsgInDB.OnActionExecuted", "微信消息记录到数据库失败");
            }
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var msg = filterContext.HttpContext.Items["wxmsg"] as RequestServiceModel;
            if (msg != null)
            {
                //使用多线程方法，让主线程继续执行
                sending = new Thread(this.CheckMsg);
                ////前台线程
                sending.IsBackground = false;
                sending.Start(msg);
            }
        }
    }
}
